package com.yan.token.repository.jpa;

import com.yan.token.module.App;
import com.yan.token.repository.AppRepository;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaDelete;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author yanheng
 * @data 2020/1/6 14:40
 */
@Repository
@Profile("jpa")
public class JpaAppRepositoryImpl implements AppRepository {


    @PersistenceContext
    private EntityManager em;

    @Override
    public App findByAppId(String appId) {
        Query query = em.createQuery("select app from App app where appId = :appId");
        query.setParameter("appId", appId);
        return (App) query.getSingleResult();
    }

    @Override
    public App findById(String id) {
//        return em.find(App.class, id);
        Query query = em.createQuery("select app  from App app where id = :id");
        query.setParameter("id", id);
        return (App) query.getSingleResult();
    }

    @Override
    public void save(App app) {
        em.persist(app);
    }

    @Override
    public Collection<App> findAll() {
        Query query = em.createQuery("select app from App app");
        return query.getResultList();
    }

    @Override
    public void deleteById(String id) {
        App app = this.findById(id);
//        Query query = em.createQuery("delete from App app where id = :id");
//        query.setParameter("id", id);
//        query.executeUpdate();

//        if (em.contains(app)){
//            em.remove(app);
//        }

    }
}
